package me.zhengjie.modules.xiao.rest;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.domain.vo.UserQueryCriteria;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.xiao.domain.CgFollowupform;
import me.zhengjie.modules.xiao.domain.CgGoods;
import me.zhengjie.modules.xiao.domain.vo.CgGoodsQueryCriteria;
import me.zhengjie.modules.xiao.service.CgGoodsService;
import me.zhengjie.utils.PageResult;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.VxMsg;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author CY
* @date 2024-07-23
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "订单管理")
@RequestMapping("/api/cgGoods")
public class CgGoodsController {

    private final CgGoodsService cgGoodsService;
    private final UserService userService;
    private final DeptService deptService;
    private final VxMsg vxMsg;
    private final DictDetailService dictDetailService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('cgGoods:list')")
    public void exportCgGoods(HttpServletResponse response, CgGoodsQueryCriteria criteria) throws IOException {
        cgGoodsService.download(cgGoodsService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询订单")
    @ApiOperation("查询订单")
    @PreAuthorize("@el.check('cgGoods:list')")
    public ResponseEntity<PageResult<CgGoods>> queryCgGoods(CgGoodsQueryCriteria criteria, Page<Object> page){
        JwtUserDto userDetails = (JwtUserDto)SecurityUtils.getCurrentUser();
        List<Long> jobs = userDetails.getUser().getJobs().stream().map(Job::getId).collect(Collectors.toList());
        Long deptId = userDetails.getUser().getDept().getId();
        Integer level = userDetails.getLevel();
        if(jobs.contains(8L)){
            if (level == 3||level == 4) {
                UserQueryCriteria userCriteria = new UserQueryCriteria();
                List<Dept> data = deptService.findByPid(deptId);
                // 然后把子节点的ID都加入到集合中
                userDetails.getDataScopes().get(0);
                List<Long> deptIds = deptService.getDeptChildren(data);
                deptIds.add(deptId);
                deptIds.retainAll(userDetails.getDataScopes());
                userCriteria.getDeptIds().addAll(deptIds);
                if(level == 3){
                   deptIds.add(0L);
                }
                criteria.getDeptIds().addAll(deptIds);
                criteria.getCreateBys().add(userDetails.getUser().getUsername());
            }
        }else{
            criteria.getCreateBys().add(userDetails.getUser().getUsername());
        }
        PageResult<CgGoods> pageResult = cgGoodsService.queryAll(criteria,page);
        for(CgGoods entity:pageResult.getContent()){
            User user = userService.findByName(entity.getCreateBy());
            if (user !=null){
               entity.setCreateUserName(user.getNickName());
            }
            if(StringUtils.isNotBlank(entity.getUpdateBy())){
                user = userService.findByName(entity.getUpdateBy());
                if (user !=null){
                   entity.setUpdateUserName(user.getNickName());
                }
            }
        }
        return new ResponseEntity<>(pageResult,HttpStatus.OK);
    }

    @PostMapping
    @Log("新增订单")
    @ApiOperation("新增订单")
    @PreAuthorize("@el.check('cgGoods:add')")
    public ResponseEntity<Object> createCgGoods(@Validated @RequestBody CgGoods resources){
        String userName = SecurityUtils.getCurrentUsername();
        Long createdeptId = SecurityUtils.getCurrentDeptId();
        String createdeptName = SecurityUtils.getCurrentDeptName();
        resources.setCreateBy(userName);
        resources.setCreateTime(DateUtil.date().toTimestamp());
        resources.setCreateDeptId(createdeptId);
        resources.setCreateDeptName(createdeptName);
        cgGoodsService.create(resources);
        DictDetail dictDetail = dictDetailService.getById(22);
        if("1".equals(dictDetail.getValue())){
            List<String> usernames = userService.getUserNameByDeptId(resources.getDeptId());
            for(String sendUserName:usernames){
                vxMsg.sendOrderMsg(sendUserName,resources.getId(),resources.getDeptName(),resources.getContent(),"","","");
            }
        }

        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PutMapping
    @Log("修改订单")
    @ApiOperation("修改订单")
    @PreAuthorize("@el.check('cgGoods:edit')")
    public ResponseEntity<Object> updateCgGoods(@Validated @RequestBody CgGoods resources){
        String userName = SecurityUtils.getCurrentUsername();
        resources.setUpdateBy(userName);
        resources.setUpdateTime(DateUtil.date().toTimestamp());
        cgGoodsService.update(resources);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @DeleteMapping
    @Log("删除订单")
    @ApiOperation("删除订单")
    @PreAuthorize("@el.check('cgGoods:del')")
    public ResponseEntity<Object> deleteCgGoods(@RequestBody List<Integer> ids) {
        cgGoodsService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping(value = "/findByid")
    @Log("订单详情")
    @ApiOperation("订单详情")
    public ResponseEntity<CgGoods> findCgCluetable(@RequestParam("id") Integer id){
        CgGoods entity= cgGoodsService.getById(id);
        return new ResponseEntity<>(entity,HttpStatus.OK);
    }
}